package MyUtil;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyUitl {
	private static SqlSessionFactory  sqlsessionfactory=null;
	static ThreadLocal<SqlSession> local=new ThreadLocal<SqlSession>();
	static{
		InputStream inputstream;
		try {
			inputstream = Resources.getResourceAsStream("mybatis-config.xml");
			sqlsessionfactory=new SqlSessionFactoryBuilder().build(inputstream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	public static SqlSession opanSession(){
		SqlSession sqlsession=sqlsessionfactory.openSession();
		return sqlsession;	
	}
	public static SqlSession getCurentSession(){
		SqlSession sqlsession=local.get();
		if(sqlsession==null){
			sqlsession=opanSession();
			local.set(sqlsession);
		}
		return sqlsession;		
	}
	//获取接口的实现类
	public static Object getMapper(Class clazz){
		SqlSession sqlsession=getCurentSession();
		return sqlsession.getMapper(clazz);
	}
	//事务提交
	public static void commit(){
		SqlSession sqlsession=getCurentSession();
		sqlsession.commit();
		sqlsession.close();
	}
	//关闭
	public static void rollback(){
		SqlSession sqlsession=getCurentSession();
		sqlsession.rollback();
		sqlsession.close();
	}
	public static void close(){
		SqlSession sqlsession=getCurentSession();
		sqlsession.close();
		local.remove();
	}
}









